package com.yexx.starter.optms.logger.utils;

import com.yexx.starter.optms.logger.common.TraceConstants;
import com.yexx.starter.optms.logger.contexts.GlobalContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Description: 分析跟踪
 *
 * @author zuomin (myleszelic@outlook.com)
 * @date: 2022/06/26-20:12
 */
@Slf4j
public final class ParseTraceUtils {

    private ParseTraceUtils() {
    }


    public static void parseHeader(HttpServletRequest request, List<String> headers) {
        if (CollectionUtils.isEmpty(headers)) {
            return;
        }
        for (String header : headers) {
            String value = request.getHeader(header);
            if (value == null) {
                continue;
            }
            GlobalContextHolder.setContext(header, value);
        }
    }

    public static void parseParam(HttpServletRequest request, List<String> params) {
        if (CollectionUtils.isEmpty(params)) {
            return;
        }
        for (String param : params) {
            String value = request.getParameter(param);
            if (value == null) {
                continue;
            }
            GlobalContextHolder.setContext(param, value);
        }
    }

    public static void parseContext(List<String> contexts) {
        if(CollectionUtils.isEmpty(contexts)) {
            return;
        }
        for (String context : contexts) {
            GlobalContextHolder.getContext(context);
        }
    }

    public static void putMDC(HttpServletRequest request) {
        MDC.put("traceId", request.getHeader(TraceConstants.TRACE_ID));
        MDC.put("userId", request.getHeader(TraceConstants.USER_ID));
        MDC.put("tenantId", request.getHeader(TraceConstants.TENANT_ID));
    }

    public static void removeDMC() {
        MDC.remove("traceId");
        MDC.remove("userId");
        MDC.remove("tenantId");
    }
}
